<template>
  <div class="test-data-entry">
    <el-card class="entry-card">
      <!-- 页面标题 -->
      <div slot="header" class="page-header">
        <h2>{{ projectName }} - 试验数据录入</h2>
        <div class="header-actions">
          <el-button type="primary" @click="saveData" :loading="saving">
            <i class="el-icon-save"></i> 保存数据
          </el-button>
          <el-button @click="resetForm">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
          <el-button @click="exportData">
            <i class="el-icon-download"></i> 导出数据
          </el-button>
          <el-button v-if="isDevelopment" @click="debugDynamicTableData" type="warning">
            <i class="el-icon-search"></i> 调试
          </el-button>
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="basic-info">
        <el-form :model="basicInfo" label-width="100px" size="medium">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检测项目">
                <el-input :value="projectName" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行标准">
                <el-input :value="standardCode" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="样品编号" required>
                <el-input
                  v-model="basicInfo.sampleNo"
                  placeholder="输入样品编号"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 动态参数组 -->
      <div class="param-groups">
        <div
          v-for="(group, groupIndex) in config.paramGroups"
          :key="group.groupId || groupIndex"
          class="param-group"
        >
          <!-- 参数组标题 -->
          <div class="group-header">
            <h3>{{ group.groupName }}</h3>
            <el-tag v-if="group.allowDynamicRows" type="info">
              动态表格（最多{{ group.maxRows }}行）
            </el-tag>
          </div>

          <!-- 嵌套组 -->
          <div v-if="group.isNested" class="nested-groups">
            <div
              v-for="(childGroup, childIndex) in group.childGroups"
              :key="childGroup.groupId || childIndex"
              class="child-group"
            >
              <h4>{{ childGroup.groupName }}</h4>
              <param-group-form
                v-if="childGroup.paramItems && childGroup.paramItems.length"
                :params="childGroup.paramItems"
                :data="getChildGroupData(groupIndex, childIndex)"
                :group-path="`groups.${groupIndex}.childGroups.${childIndex}`"
                @data-change="handleDataChange"
                @calculate="handleCalculate"
              />
              <div v-else class="empty-param-group">该组暂无参数配置</div>
            </div>
          </div>

          <!-- 非嵌套组 -->
          <div v-else>
            <param-group-form
              v-if="group.paramItems && group.paramItems.length"
              :params="group.paramItems"
              :data="getGroupData(groupIndex)"
              :group-path="`groups.${groupIndex}`"
              :allow-dynamic-rows="group.allowDynamicRows"
              :max-rows="group.maxRows"
              @data-change="handleDataChange"
              @calculate="handleCalculate"
            />
            <div v-else class="empty-param-group">该组暂无参数配置</div>
          </div>
        </div>
      </div>

      <!-- 数据预览 -->
      <div class="data-preview">
        <el-collapse>
          <el-collapse-item title="数据预览">
            <pre class="preview-json">{{ formattedData }}</pre>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script>
import ParamGroupForm from '@/components/ParamGroupForm.vue'
import FormulaCalculator from '@/utils/FormulaCalculator'
import DataFlattener from '@/utils/dataFlattener'
export default {
  name: 'TestDataEntry',
  components: { ParamGroupForm },
  props: {
    config: {
      type: Object,
      required: true,
      default: () => ({ paramGroups: [] })
    }
  },
  data() {
    return {
      basicInfo: { sampleNo: '' },
      formData: { groups: [] },
      saving: false,
      formulaCalculator: new FormulaCalculator()
    }
  },
  computed: {
    formattedData() {
      return JSON.stringify(
        { basicInfo: this.basicInfo, testData: this.formData },
        null,
        2
      )
    },
    projectName() {
      return this.config.projectName || '未命名项目'
    },
    standardCode() {
      return this.config.standardCode || '无'
    },
    isDevelopment() {
      return process.env.NODE_ENV === 'development'
    }
  },
  watch: {
    config: {
      handler: 'initializeFormData',
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * 获取组数据（统一数据访问接口）
     */
    getGroupData(groupIndex) {
      if (!this.formData.groups[groupIndex]) {
        return {}
      }
      return this.formData.groups[groupIndex]
    },

    /**
     * 获取子组数据（统一数据访问接口）
     */
    getChildGroupData(groupIndex, childIndex) {
      const group = this.formData.groups[groupIndex]
      if (!group || !group.childGroups || !group.childGroups[childIndex]) {
        return {}
      }
      return group.childGroups[childIndex]
    },

    /**
     * 统一初始化表单数据结构
     */
    initializeFormData(config) {
  if (!config.paramGroups || !config.paramGroups.length) {
    this.formData.groups = []
    return
  }

  this.formData.groups = config.paramGroups.map((group, groupIndex) => {
    const groupData = {
      groupId: group.groupId,
      groupName: group.groupName,
      params: this.initializeParams(group.paramItems || [])
    }

    // 嵌套组处理 - 修复：确保正确初始化嵌套结构
    if (group.isNested) {
      groupData.childGroups = (group.childGroups || []).map((childGroup, childIndex) => {
        console.log(`初始化嵌套组: 组${groupIndex}子组${childIndex}`, childGroup.paramItems)
        return {
          groupId: childGroup.groupId,
          groupName: childGroup.groupName,
          params: this.initializeParams(childGroup.paramItems || [])
        }
      })
    }

    // 动态表格处理 - 修复：确保正确初始化行数据
    if (group.allowDynamicRows) {
      groupData.rows = [this.initializeParams(group.paramItems || [])]
    }

    return groupData
  })

  console.log('初始化后的完整表单数据结构:', JSON.parse(JSON.stringify(this.formData.groups)))
  
  // 初始化后立即计算一次所有计算参数
  this.$nextTick(() => {
    this.calculateAllComputedParams()
  })
},

    /**
     * 初始化参数数据结构
     */
    initializeParams(params) {
      const paramsData = {}
      if (!Array.isArray(params)) return paramsData

      params.forEach((param) => {
        if (!param.paramCode) return

        if (param.isMultiMeasure && param.multiMeasureCount > 1) {
          paramsData[param.paramCode] = Array.from(
            { length: param.multiMeasureCount },
            () => ({ value: '', isValid: true, message: '' })
          )
        } else {
          paramsData[param.paramCode] = {
            value: '',
            isValid: true,
            message: ''
          }
        }
      })

      return paramsData
    },

     /**
     * 统一参数值查找方法（修复非动态表格多测次参数查找）
     */
    findParamValue(paramCode, context = {}) {
      const { groupIndex, childGroupIndex, rowIndex, measureIndex } = context
      
      console.log(`[查找参数] ${paramCode}`, context)
      // 1. 按上下文精准查找
      if (groupIndex !== undefined) {
        const group = this.formData.groups[groupIndex]
        if (!group) {
          console.warn(`[查找失败] 组 ${groupIndex} 不存在`)
          return undefined
        }
        // 动态表格行
        if (rowIndex !== undefined) {
          if (group.rows && group.rows[rowIndex]) {
            const value = this.extractParamValue(group.rows[rowIndex][paramCode], measureIndex)
            if (value !== undefined) {
              console.log(`[精准找到] 动态表格行 ${rowIndex} 参数 ${paramCode}:`, value)
              return value
            }
          }
        }
        // 嵌套子组
        if (childGroupIndex !== undefined) {
          if (group.childGroups && group.childGroups[childGroupIndex]) {
            const value = this.extractParamValue(
              group.childGroups[childGroupIndex].params[paramCode], 
              measureIndex
            )
            if (value !== undefined) {
              console.log(`[精准找到] 子组 ${childGroupIndex} 参数 ${paramCode}:`, value)
              return value
            }
          }
        }
        // 普通组参数（重点修复：支持多测次参数）
        const value = this.extractParamValue(group.params[paramCode], measureIndex)
        if (value !== undefined) {
          console.log(`[精准找到] 普通组参数 ${paramCode}:`, value)
          return value
        }
      }
      // 2. 全局查找（备用方案）- 修复版本
      console.log(`[全局查找] 参数 ${paramCode}`)
      for (let gIndex = 0; gIndex < this.formData.groups.length; gIndex++) {
        const group = this.formData.groups[gIndex]
        
        // 检查普通组参数（支持多测次）
        if (group.params && group.params[paramCode] !== undefined) {
          const value = this.extractParamValue(group.params[paramCode], measureIndex)
          console.log(`[全局找到] 组 ${gIndex} 普通参数 ${paramCode}:`, value)
          return value
        }
        // 检查嵌套子组
        if (group.childGroups) {
          for (let cIndex = 0; cIndex < group.childGroups.length; cIndex++) {
            const childGroup = group.childGroups[cIndex]
            if (childGroup.params && childGroup.params[paramCode] !== undefined) {
              const value = this.extractParamValue(childGroup.params[paramCode], measureIndex)
              console.log(`[全局找到] 组 ${gIndex} 子组 ${cIndex} 参数 ${paramCode}:`, value)
              return value
            }
          }
        }
        // 检查动态表格行
        if (group.rows) {
          for (let rIndex = 0; rIndex < group.rows.length; rIndex++) {
            const row = group.rows[rIndex]
            if (row[paramCode] !== undefined) {
              const value = this.extractParamValue(row[paramCode], measureIndex)
              console.log(`[全局找到] 组 ${gIndex} 行 ${rIndex} 参数 ${paramCode}:`, value)
              return value
            }
          }
        }
      }
      console.warn(`[参数未找到] ${paramCode}`)
      return undefined
    },

    /**
     * 从参数数据中提取实际值（增强多测次参数支持）
     */
    extractParamValue(paramData, measureIndex = null) {
      if (!paramData) return undefined
      
      // 重点修复：多测次参数处理（数组格式）
      if (Array.isArray(paramData)) {
        // 1. 指定测次索引：直接返回对应测次值
        if (measureIndex !== null && measureIndex >= 0 && measureIndex < paramData.length) {
          const item = paramData[measureIndex]
          return item ? this.normalizeValue(item.value) : ''
        }
        // 2. 未指定测次索引：返回完整的测次值数组（供计算函数使用）
        return paramData.map(item => item ? this.normalizeValue(item.value) : '').filter(val => val !== '')
      }
      
      // 普通参数
      return this.normalizeValue(paramData.value)
    },

    /**
     * 值标准化处理
     */
    normalizeValue(value) {
      if (value === '' || value === null || value === undefined) return ''
      const numValue = Number(value)
      return isNaN(numValue) ? value : numValue
    },

    /**
     * 统一参数更新方法
     */
        updateParamValue(param, value, isValid = true, message = '', context = {}) {
      const { groupIndex, childGroupIndex, rowIndex, measureIndex } = context
      
      console.log(`[更新参数] ${param.paramCode}`, { value, context })

      // 参数校验
      if (!param || !param.paramCode) {
        console.error('参数配置无效')
        return
      }

      if (groupIndex === undefined) {
        console.error('缺少组索引', { paramCode: param.paramCode, context })
        return
      }

      const group = this.formData.groups[groupIndex]
      if (!group) {
        console.error(`组 ${groupIndex} 不存在`)
        return
      }

      let targetParams = null
      let updatePath = ''

      // 确定目标参数容器
      if (rowIndex !== undefined) {
        // 动态表格行
        if (!group.rows || !group.rows[rowIndex]) {
          console.error(`动态表格行 ${rowIndex} 不存在`)
          return
        }
        targetParams = group.rows[rowIndex]
        updatePath = `groups.${groupIndex}.rows.${rowIndex}`
      } else if (childGroupIndex !== undefined) {
        // 嵌套子组
        if (!group.childGroups || !group.childGroups[childGroupIndex]) {
          console.error(`嵌套子组 ${childGroupIndex} 不存在`)
          return
        }
        targetParams = group.childGroups[childGroupIndex].params
        updatePath = `groups.${groupIndex}.childGroups.${childGroupIndex}.params`
      } else {
        // 普通组
        targetParams = group.params
        updatePath = `groups.${groupIndex}.params`
      }

      // 检查参数是否存在
      if (!targetParams || targetParams[param.paramCode] === undefined) {
        console.warn(`参数 ${param.paramCode} 在目标位置不存在`, { 
          targetParams: Object.keys(targetParams || {}),
          updatePath 
        })
        return
      }

      // 更新参数值
      this.updateSingleParam(targetParams[param.paramCode], value, isValid, message, measureIndex)

      // 触发响应式更新
      this.$forceUpdate()
      
      console.log(`[更新成功] ${param.paramCode}`, targetParams[param.paramCode])
    },


    /**
     * 更新单个参数值
     */
    updateSingleParam(paramData, value, isValid, message, measureIndex) {
      if (Array.isArray(paramData)) {
        // 多测次参数
        if (measureIndex !== null && measureIndex < paramData.length) {
          this.$set(paramData[measureIndex], 'value', value)
          this.$set(paramData[measureIndex], 'isValid', isValid)
          this.$set(paramData[measureIndex], 'message', message)
        } else {
          paramData.forEach(item => {
            this.$set(item, 'value', value)
            this.$set(item, 'isValid', isValid)
            this.$set(item, 'message', message)
          })
        }
      } else {
        // 普通参数
        this.$set(paramData, 'value', value)
        this.$set(paramData, 'isValid', isValid)
        this.$set(paramData, 'message', message)
      }
    },

      /**
     * 计算单个参数（修复非动态表格多测次参数计算）
     */
    calculateSingleParam(param, dependencies, context = {}) {
      try {
        const { groupIndex, childGroupIndex, rowIndex, measureIndex } = context
        console.log(`[计算上下文]`, { groupIndex, childGroupIndex, rowIndex, measureIndex })
        console.log(`[计算开始] ${param.paramName}`, { 
          dependencies, 
          context,
          calculationExpr: param.calculationExpr 
        })
        const dependencyValues = {}
        const missingDeps = []
        
        // 修复核心：区分动态表格和普通表格的依赖处理
        if (rowIndex !== undefined) {
          // 动态表格：原有逻辑保持不变
          console.log(`[动态表格计算] 组${groupIndex}行${rowIndex}参数${param.paramCode}`)
          const group = this.formData.groups[groupIndex]
          if (!group || !group.rows || !group.rows[rowIndex]) {
            console.error(`[计算失败] 动态表格行不存在: 组${groupIndex}行${rowIndex}`)
            return
          }
          const rowData = group.rows[rowIndex]
          dependencies.forEach(depCode => {
            if (rowData[depCode] !== undefined) {
              if (Array.isArray(rowData[depCode])) {
                const measureValues = rowData[depCode].map(item => {
                  const numValue = Number(item.value)
                  return isNaN(numValue) ? 0 : numValue
                })
                dependencyValues[depCode] = measureValues
              } else {
                const numValue = Number(rowData[depCode].value)
                dependencyValues[depCode] = isNaN(numValue) ? 0 : numValue
              }
            } else {
              missingDeps.push(depCode)
              dependencyValues[depCode] = 0
            }
          })
        } else {
          // 非动态表格：支持多测次参数依赖
          console.log(`[普通表格计算] 组${groupIndex}参数${param.paramCode}`)
          dependencies.forEach(depCode => {
            // 查找依赖参数的所有测次值
            const depValues = this.findParamValue(depCode, { groupIndex, childGroupIndex })
            if (Array.isArray(depValues) && depValues.length > 0) {
              // 多测次参数：传递完整数组供计算
              dependencyValues[depCode] = depValues
              console.log(`[普通表格依赖] ${depCode}:`, depValues)
            } else if (depValues !== undefined && depValues !== '') {
              // 普通参数：传递单个值
              dependencyValues[depCode] = depValues
            } else {
              missingDeps.push(depCode)
              dependencyValues[depCode] = 0
            }
          })
        }
        
        // 处理缺失依赖
        if (missingDeps.length > 0) {
          console.warn(`缺失依赖参数: ${missingDeps.join(', ')}`)
        }
        
        // 修正表达式（移除.value后缀）
        let calculationExpr = this.fixDynamicTableExpression(param.calculationExpr)
        console.log(`[修正后的表达式] ${calculationExpr}`)
        
        // 执行计算
        const rawResult = this.formulaCalculator.calculate(
          calculationExpr,
          dependencyValues,
          { precision: param.precision || 2 }
        )
         // 根据数据类型决定最终返回值
        let finalResult
        if (param.dataType === 'text') {
          // 文本类型：直接返回原始结果（支持字符串拼接等）
          finalResult = rawResult == null ? '' : String(rawResult)
        } else {
          // 数字类型：保留原有精度处理
          finalResult = isNaN(rawResult) ? 0 : Number(rawResult.toFixed(param.precision || 2))
        }
        const message = missingDeps.length > 0 ? `缺失依赖: ${missingDeps.join(', ')}` : ''
        console.log(`[计算结果] ${param.paramName}: ${finalResult}`, { 
          dependencies: dependencyValues,
          originalExpr: param.calculationExpr,
          finalExpr: calculationExpr
        })
        
        // 更新计算结果
        this.updateParamValue(param, finalResult, true, message, context)
      } catch (error) {
        console.error(`[计算失败] ${param.paramName}:`, error)
        this.updateParamValue(param, 0, false, `计算错误: ${error.message}`, context)
      }
    },

/**
 * 修正动态表格中的计算表达式
 * 将 a_ddoi[0].value 格式转换为计算引擎能理解的形式
 */
fixDynamicTableExpression(expression) {
  if (!expression) return expression
  
  // 将 a_ddoi[0].value 替换为 a_ddoi[0]
  // 因为我们在 dependencyValues 中传递的是数值数组
  let fixedExpr = expression.replace(/\.value/g, '')
  
  console.log(`[表达式修正] ${expression} -> ${fixedExpr}`)
  return fixedExpr
},

   /**
     * 计算所有计算参数（修复非动态表格多测次计算触发）
     */
    calculateAllComputedParams() {
      console.log('[重新计算所有参数]')
      
      this.config.paramGroups.forEach((group, groupIndex) => {
        if (group.allowDynamicRows) {
          // 动态表格：原有逻辑保持不变
          const groupData = this.formData.groups[groupIndex]
          if (groupData && groupData.rows) {
            console.log(`[计算动态表格] 组${groupIndex}有${groupData.rows.length}行`)
            groupData.rows.forEach((row, rowIndex) => {
              console.log(`[计算行] 组${groupIndex}行${rowIndex}`)
              let gropItems = group.paramItems || [];
               gropItems.forEach(param => {
                if (param.paramType === 'calculation' && param.calculationExpr) {
                  this.calculateSingleParam(param, param.dependencies || [], {
                    groupIndex,
                    rowIndex
                  })
                }
              })
            })
          }
        } else if (group.isNested) {
          // 嵌套组：原有逻辑保持不变
           let childGroups = group.childGroups || [];
          childGroups.forEach((childGroup, childIndex) => {
            (childGroup.paramItems || []).forEach(param => {
              if (param.paramType === 'calculation' && param.calculationExpr) {
                this.calculateSingleParam(param, param.dependencies || [], {
                  groupIndex,
                  childGroupIndex: childIndex
                })
              }
            })
          })
        } else {
          // 普通组：修复多测次参数计算
          console.log(`[计算普通组] 组${groupIndex}（支持多测次参数）`)
           let gropItems = group.paramItems || [];
          gropItems.forEach(param => {
            if (param.paramType === 'calculation' && param.calculationExpr) {
              this.calculateSingleParam(param, param.dependencies || [], { 
                groupIndex 
              })
            }
          })
        }
      })
    },

    /**
     * 处理数据变化
     */
    handleDataChange({ groupPath, data }) {
      console.log('[数据变化]', { groupPath, data })

      const pathArray = groupPath.split('.')
      let current = this.formData

      // 导航到目标路径
      for (let i = 0; i < pathArray.length - 1; i++) {
        const key = pathArray[i]
        if (!current[key]) {
          this.$set(current, key, i === pathArray.length - 2 ? {} : [])
        }
        current = current[key]
      }

      const lastKey = pathArray[pathArray.length - 1]
      
      // 合并数据（保留原有结构）
      if (data.rows) {
        // 动态表格数据
        this.$set(current, lastKey, { ...current[lastKey], rows: data.rows })
      } else if (data.params) {
        // 参数数据
        this.$set(current, lastKey, { ...current[lastKey], params: data.params })
      } else {
        // 其他数据
        this.$set(current, lastKey, { ...current[lastKey], ...data })
      }

      // 延迟触发计算
      this.$nextTick(() => {
        this.calculateAllComputedParams()
      })
    },

    /**
     * 处理计算请求
     */
    handleCalculate(calculationData) {
      console.log('[计算请求]', calculationData)
      
      if (calculationData.dependentCalculations) {
        // 批量计算请求（来自动态表格）
        calculationData.dependentCalculations.forEach(param => {
          this.calculateSingleParam(param, param.dependencies || [], {
            groupIndex: calculationData.groupIndex,
            rowIndex: calculationData.rowIndex
          })
        })
      } else {
        // 单个计算请求
        this.calculateSingleParam(
          calculationData.param, 
          calculationData.dependencies || [], 
          {
            groupIndex: calculationData.groupIndex,
            childGroupIndex: calculationData.childGroupIndex,
            rowIndex: calculationData.rowIndex,
            measureIndex: calculationData.measureIndex
          }
        )
      }
    },

     /**
     * 验证整个表单
     */
    validateForm() {
      let isValid = true
      const errorMessages = []

      // 1. 验证基本信息
      if (!this.basicInfo.sampleNo.trim()) {
        isValid = false
        errorMessages.push('样品编号为必填项')
      }

      // 2. 验证所有参数
      this.config.paramGroups.forEach((group, groupIndex) => {
        const validateGroupParams = (params, context = {}) => {
          params.forEach(param => {
            const value = this.findParamValue(param.paramCode, context)
            const validation = this.validateSingleParam(value, param)
            
            if (!validation.isValid) {
              isValid = false
              errorMessages.push(`${param.paramName || param.paramCode}: ${validation.message}`)
              
              // 更新参数验证状态
              this.updateParamValue(param, value, false, validation.message, context)
            }
          })
        }

        if (group.allowDynamicRows) {
          // 动态表格验证
          const groupData = this.formData.groups[groupIndex]
          if (groupData && groupData.rows) {
            groupData.rows.forEach((row, rowIndex) => {
              validateGroupParams(group.paramItems, { groupIndex, rowIndex })
            })
          }
        } else if (group.isNested) {
          // 嵌套组验证
          group.childGroups.forEach((childGroup, childIndex) => {
            validateGroupParams(childGroup.paramItems, { groupIndex, childGroupIndex: childIndex })
          })
        } else {
          // 普通组验证
          validateGroupParams(group.paramItems, { groupIndex })
        }
      })

      return { isValid, errorMessages }
    },

    /**
     * 验证单个参数
     */
    validateSingleParam(value, param) {
      const rules = param.validateRule || {}
      let isValid = true
      let message = ''

      // 必填验证
      if (rules.required && (value === '' || value === null || value === undefined)) {
        isValid = false
        message = rules.requiredMsg || `${param.paramName}为必填项`
        return { isValid, message }
      }

      // 空值且非必填时直接通过
      if (value === '' || value === null || value === undefined) {
        return { isValid: true, message: '' }
      }

      // 数值范围验证
      if (param.dataType === 'number') {
        const numValue = Number(value)
        
        if (!isNaN(numValue)) {
          if (rules.min !== undefined && numValue < rules.min) {
            isValid = false
            message = rules.rangeMsg || `${param.paramName}不能小于 ${rules.min}${param.unit || ''}`
          }
          
          if (isValid && rules.max !== undefined && numValue > rules.max) {
            isValid = false
            message = rules.rangeMsg || `${param.paramName}不能大于 ${rules.max}${param.unit || ''}`
          }
        }
      }

      return { isValid, message }
    },

     /**
     * 保存数据 - 增强验证
     */
    async saveData() {
      // 执行表单验证
      const validation = this.validateForm()
      if (!validation.isValid) {
        this.$message.error(`请修正以下问题：\n${validation.errorMessages.join('\n')}`)
        return
      }

      this.saving = true
      try {
       const saveData = {
          basicInfo: this.basicInfo,
          testData: this.formData,
          projectId: this.config.projectId,
          projectName: this.projectName,
          standardCode: this.standardCode,
          timestamp: new Date().toISOString()
        }

        // 打印保存的数据（实际项目中替换为API请求）
        console.log('保存的数据:', JSON.stringify(saveData))
         const flatData = DataFlattener.flattenTestData(saveData)
         const res = await this.$http({
          method: 'post',
          url: '/api/lims/excel/download', // 接口路径
          data: flatData // 请求体（会自动转为 JSON 格式，对应 Content-Type: application/json）
        })
        console.log('res:', res)
        this.$message.success('数据保存成功')
      } catch (error) {
        console.error('数据保存失败:', error)
        this.$message.error('数据保存失败，请重试')
      } finally {
        this.saving = false
      }
    },

    validateRequiredFields() {
      // 简化的验证逻辑
      if (!this.basicInfo.sampleNo.trim()) {
        return false
      }
      return true
    },

    resetForm() {
      this.$confirm('确定要重置所有数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.basicInfo.sampleNo = ''
        this.initializeFormData(this.config)
        this.$message.success('表单已重置')
      })
    },

    exportData() {
      const exportData = {
        basicInfo: this.basicInfo,
        testData: this.formData,
        projectId: this.config.projectId,
        projectName: this.projectName,
        standardCode: this.standardCode,
        exportTime: new Date().toISOString()
      }

      const blob = new Blob([JSON.stringify(exportData, null, 2)], {
        type: 'application/json;charset=utf-8'
      })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `试验数据-${this.basicInfo.sampleNo || '未知样品'}-${Date.now()}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)

      this.$message.success('数据导出成功')
    },
    /**
 * 调试动态表格数据
 */
debugDynamicTableData() {
  console.log('=== 动态表格调试信息 ===')
  
  this.config.paramGroups.forEach((group, groupIndex) => {
    if (group.allowDynamicRows) {
      console.log(`\n[动态表格组${groupIndex}] ${group.groupName}`)
      
      const groupData = this.formData.groups[groupIndex]
      if (groupData && groupData.rows) {
        groupData.rows.forEach((row, rowIndex) => {
          console.log(`[行${rowIndex}]`, JSON.parse(JSON.stringify(row)))
        })
      }
      
      // 显示计算参数配置
      const calcParams = group.paramItems.filter(p => p.paramType === 'calculation')
      calcParams.forEach(param => {
        console.log(`[计算参数] ${param.paramName}`, {
          表达式: param.calculationExpr,
          依赖: param.dependencies
        })
      })
    }
  })
},
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.test-data-entry {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.entry-card {
  border-radius: 8px;
  border: 1px solid #e6e8eb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.basic-info {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.param-groups {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 30px;
}

.param-group {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e6e8eb;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #409eff;
}

.group-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.nested-groups {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-left: 15px;
}

.child-group {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.child-group h4 {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
}

.empty-param-group {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
  background-color: #fafafa;
  border-radius: 6px;
}

.data-preview {
  margin-top: 30px;
}

.preview-json {
  background: #fafafa;
  border: 1px solid #e6e8eb;
  border-radius: 4px;
  padding: 15px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
  line-height: 1.4;
  color: #333;
  max-height: 300px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>